<template>
  <div>
    <el-upload
      v-show="!isShowProgress"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :class="{display:fileList.length}"
      :on-remove="onRemove"
      :http-request="onRequest"
      :on-change="onChange"
      :on-preview="handlePictureCardPreview"
      :before-upload="beforeUpload"
    >
      <!-- accept="image/png, image/jpeg, image/gif" -->
      <i class="el-icon-plus" />
    </el-upload>

    <!-- 进度条 -->
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  // API密钥
  SecretId: 'AKIDf9NK0QYPyHhrkMina6MK2TdXAYgY9UZO',
  SecretKey: 'ZsumOjob8NM4WhaCYcOt75lAH8i24qmR'
})
export default {
  name: 'UploadImage',
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      currentUid: '',
      percentage: 0,
      isShowProgress: false
    }
  },

  created() {

  },

  methods: {
    // 点击移除图片
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 自定义上传请求
    onRequest(data) {
      cos.putObject({
        Bucket: 'hrsaas-rz-1307760770', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        StorageClass: 'STANDARD',
        Key: data.file.name, /* 必须 名字*/
        Body: data.file, // 上传文件对象
        onProgress: progressData => {
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (err) {
          this.$message.error('上传失败，请重新上传')
          this.isShowProgress = false
          this.fileList = this.fileList.filter(item => item.uid !== this.currentUid)
        }
        console.log(err || data)
        if (!err && data.statusCode === 200) {
          const url = 'https://' + data.Location
          const index = this.fileList.findIndex(item => {
            return item.uid === this.currentUid
          })
          this.fileList[index].url = url
          // 通过 $emit 将数据传递到父组件
          this.$emit('on-success', this.fileList, url)
          setTimeout(() => {
            this.isShowProgress = false
          }, 500)
        }
      })
    },
    // 本地上传成功
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 点击预览
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    // 选中图片之前限制图片大小
    beforeUpload(file) {
      const maxSize = 1 * 1024 * 1024 // 限制1MB内
      const type = ['image/png', 'image/jpeg', 'image/gif'] // 限制图片格式
      if (!type.includes(file.type)) {
        this.$message.error('请选择正确的图片')
        return false
      }
      if (file.size >= maxSize) {
        this.$message.error('请选择1MB以内的图片')
        return false
      }
      this.currentUid = file.uid
      this.isShowProgress = true
      return true
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .display .el-upload--picture-card{
  display: none;
}
</style>
